﻿using System;
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;
using Backend;
using Frontend;
using MiddleWares;
using ProgramLexer = Frontend.ProgramLexer;
using ProgramParser = Frontend.ProgramParser;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string test = @"
void delay(void) {
	int c;
	c = 255;
	while (c) {
		c = c - 1;
	}
}
void main(void) {
	int led;
	int wait;
	wait = 3000;
	led = 1;
	led = led << 1;
	while (1)
	{
		while (wait) {
			$0XFFFFFC60 = led >> 1;
			wait = wait - 1;
		}
		delay();
		wait = 3000;
		while (wait) {
				$0XFFFFFC60 = led << 1;
				wait = wait - 1;
        }
	}
}
";

            ICharStream stream = CharStreams.fromString(test);
            ITokenSource lexer = new ProgramLexer(stream);
            ITokenStream tokens = new CommonTokenStream(lexer);
            ProgramParser parser = new ProgramParser(tokens)
            {
                BuildParseTree = true,
                // ErrorHandler = new FrontEndErrorStrategy()
            };
            IParseTree tree = parser.program();
            var walker = new ParseTreeWalker();
            var frontEndListener = new FrontEndListener();
            walker.Walk(frontEndListener, tree);
            Console.WriteLine(frontEndListener.Result);

            var rlt = frontEndListener.Result;
            Console.WriteLine(rlt);

            // rlt = MergeLabel.Merge(rlt);
            // Console.WriteLine(rlt);

            ICharStream bstream = CharStreams.fromString(rlt);
            ITokenSource blexer = new Backend.ProgramLexer(bstream);
            ITokenStream btokens = new CommonTokenStream(blexer);
            Backend.ProgramParser bparser = new Backend.ProgramParser(btokens)
            {
                BuildParseTree = true,
                // ErrorHandler = new FrontEndErrorStrategy()
            };

            IParseTree bTree = bparser.program();
            var bWalker = new ParseTreeWalker();
            var backendListener = new BackendListener();
            bWalker.Walk(backendListener, bTree);

            Console.WriteLine(string.Join("\n", backendListener.Result));
        }
    }
}